<template>
  <div class="app-container">

    <el-row :gutter="20">
      <!--  服务方接口列表    -->
      <SupplierHeadTree :dataList="supplierPortList" @chooseTreeData="handleNodeClick"  />

      <el-col :span="20" class="right" v-if="chooseExcPort.type != 2 ">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">

          <el-form-item label="参数类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择参数类型" @change="changeExcPortType">
              <el-option v-for="type in  extPortConfigType" :key="type.value" :value="type.value"
                         :label="type.name"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button icon="el-icon-delete" :disabled="deleteButtonStatus" type="danger" plain size="mini"
                       @click="delExcPortConfigType"
            >删除
            </el-button>

            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport(1)"
              :disabled="importConfig.disabled"
              v-show="queryParams.type != 3"
            >全量导入
            </el-button>

            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport(2)"
              :disabled="importConfig.disabled"
              v-show="queryParams.type != 3"
            >增量导入
            </el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>


        <el-table v-loading="loading" :data="excPortConfigList" row-key="rowKey"
                  ref="excPortConfigTable"
                  border
                  default-expand-all
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  height="620"
        >

          <el-table-column label="字段" align="left" prop="field" show-overflow-tooltip />
          <el-table-column label="字段名称" align="center" prop="fieldName" width="150"/>
          <el-table-column label="字段类型" align="center" width="80">
            <template slot-scope="scope">
              {{ getFieldTypeName(scope.row.fieldType) }}
            </template>
          </el-table-column>

          <el-table-column align="center">
            <template slot="header" slot-scope="scope">
              <span>模拟值</span>&nbsp;&nbsp;&nbsp;&nbsp;
<!--              <el-button size="mini" type="primary" plain round @click="handleSumbitMappingFormula">提交</el-button>-->
            </template>

            <template slot-scope="scope">
              <input type="text" class="mappingFormulaInput"
                     :value="scope.row.mappingFormula"
                     :ref="scope.row.rowKey"
                     v-direction="{x: 0, y: scope.$index, row: scope.row}"
                     @focus="handleFocusFormula(scope.row, $event)"
                     @change="handleInputValue( scope.row.rowKey )"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" alignhandleFocusFormula="center" width="150"
                           class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleFiledAdd(scope.row, 1)"
              >新增
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleFiledAdd(scope.row, 2)"
                v-if="scope.row.fieldType != 1"
              >新增子级
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleFiledUpdate(scope.row)"
                v-hasPermi="['pm:excPortConfig:edit']"
              >修改
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['pm:excPortConfig:remove']"
                v-if="chooseExcPort.type != 4"
              >删除
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-top"
                @click="handleSort(scope.row, 'up')"
              >
                向上
              </el-button>

              <el-button size="mini" type="text" icon="el-icon-bottom"
                         @click="handleSort(scope.row, 'down')"
              >
                向下
              </el-button>
            </template>


          </el-table-column>
        </el-table>

      </el-col>

      <el-col :span="20" class="right" v-if="chooseExcPort.type == 2">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">

          <el-form-item label="参数类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择参数类型" @change="changeExcPortType">
              <el-option v-for="type in  extPortConfigType" :key="type.value" :value="type.value"
                         :label="type.name"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button icon="el-icon-delete" :disabled="deleteButtonStatus" type="danger" plain size="mini"
                       @click="delExcPortConfigType"
            >删除
            </el-button>

            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport(1)"
              :disabled="importConfig.disabled"
              v-show="!importConfig.disabled"
            >全量导入
            </el-button>

            <el-button
              type="primary"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport(2)"
              :disabled="importConfig.disabled"
              v-show="!importConfig.disabled"
            >增量导入
            </el-button>
            <el-button size="mini"
                       plain
                       type="success"
                       icon="el-icon-plus"
                       @click="handleRule()"
            >
              报错规则
            </el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="excPortConfigList" row-key="id"
                  border
                  default-expand-all
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  height="620"
        >

          <el-table-column label="字段" align="center" prop="field"/>
          <el-table-column label="字段名称" align="center" prop="fieldName"/>
          <el-table-column label="字段类型" align="center">
            <template slot-scope="scope">
              {{ getFieldTypeName(scope.row.fieldType) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" alignhandleFocusFormula="center"
                           class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleFiledAdd(scope.row, 1)"
              >新增
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleFiledAdd(scope.row, 2)"
                v-if="scope.row.fieldType != 1"
              >新增子级
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleFiledUpdate(scope.row)"
                v-hasPermi="['pm:excPortConfig:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['pm:excPortConfig:remove']"
              >删除
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-top"
                :disabled="scope.row.orderNum == 1 ? true : false"
                @click="handleSort(scope.row, 'up')"
              >
                向上
              </el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-bottom"
                @click="handleSort(scope.row, 'down')"
              >
                向下
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>

    </el-row>

    <!--  导入弹框  -->
    <el-dialog :title="importConfig.title" :visible.sync="importConfig.open" width="700px" append-to-body>
      <importData @cancalImportDialog="cancalImportDialog"
                  @submitImport="submitImport"
                  :portId="queryParams.portId"
                  :type="queryParams.type"
                  :saveType="importConfig.type"
      />
    </el-dialog>

    <!-- 新增字段   -->
    <el-dialog :title="fieldDialog.title" :visible.sync="fieldDialog.open" width="680px" append-to-body>
      <el-form ref="fieldForm" :model="fieldForm" :rules="fieldFormRules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级字段">
              <el-input :value="parentFieldName" placeholder="请输入上级字段" disabled/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="字段" prop="field">
              <el-input v-model="fieldForm.field" placeholder="请输入字段"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="字段名称" prop="fieldName">
              <el-input v-model="fieldForm.fieldName" placeholder="请输入字段名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="字段类型" prop="fieldType">
              <el-select v-model="fieldForm.fieldType" placeholder="请选择字段类型">
                <el-option
                  v-for="item in fieldTypeList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>

            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFieldForm">确 定</el-button>
        <el-button @click="fieldDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改字段的弹窗   -->
    <el-dialog :title="updateField.title" :visible.sync="updateField.open" width="500px" append-to-body>
      <EditField
        :updateForm="updateForm"
        :allListSupplierList="allListSupplierList"
        @updateFieldForm="updateFieldForm"
        @cancelFieldForm="cancelFieldForm"/>
    </el-dialog>

  </div>
</template>

<script>
import {
  listExcPortConfig,
  getExcPortConfig,
  delExcPortConfig,
  addExcPortConfig,
  updateExcPortConfig,
  delExcPortConfigType,
  updateExcPortConfigMappingFormula,
  updateExcPortConfigOrderNum,
  addStandardOrderList
} from "@/api/pm/excPortConfig";
import {listSupplier} from "@/api/pm/supplier";
import {listExcPort} from "@/api/pm/excPort";

import MyCodeMirror from '@/components/CodeMirror/index.vue';

import EditField from "@/views/pm/excPortConfig/editField";
import importData from "@/views/pm/excPortConfig/importData";

import {list2FieldTree, dealExcPortTree} from './js/common';
import {extPortConfigType, fieldTypeList} from './js/type';

// 混入
import excPortImport from '@/mixin/excPortConfig/import';

import SupplierHeadTree from "@/components/HeadTree/supplierHead";
import {getAlllistSupplierMain} from "@/api/pm/supplierMain";


export default {
  name: "ExcPortConfig",
  components: {MyCodeMirror, EditField, importData, SupplierHeadTree},
  mixins: [excPortImport],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 接口参数配置表格数据
      excPortConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        portId: null,
        ancestors: null,
        parentId: null,
        fieldName: null,
        type: 1,
        column: null,
        columnType: null,
        defaultValue: null
      },
      // 表单参数
      form: {},

      // 选中的服务方接口
      supplierExcPort: '',


      // 服务方方法列表
      excPortList: [],
      excPortOriginalList: [],

      // 删除允许删除
      deleteButtonStatus: true,

      // 选中的信息
      chooseExcPort: {
        // 选中的接口id
        id: '',
        name: '',
        // 选中的接口类型
        type: 1,
        typeName: '',
        supplierType: '',
      },

      extPortConfigType,

      // 新增的参数
      fieldDialog: {
        parentId: '',
        open: false,
        title: '新增字段'
      },
      fieldForm: {
        parentId: '',
        ancestors: '',
        field: '',
        fieldName: '',
        // orderNum: 1,
        fieldType: 1
      },

      fieldTypeList,

      // 上级字段名称
      parentFieldName: '',

      fieldFormRules: {
        field: [
          {required: true, message: '字段不能为空', tigger: 'blur'}
        ],
        fieldName: [
          {required: true, message: '字段名称不能为空', tigger: 'blur'}
        ]
      },

      // 修改字段
      updateField: {
        open: false,
        title: '修改字段'
      },

      // 修改字段的内容
      updateForm: [],
      // 选择的险种格式

      // updateFieldRisks: {},
      fieldRisks: [],

      // 选中的字段
      chooseFieldData: {},
      //mappingFormulaClass: 'mappingFormulaClass',
      tableShow: true,

      // 选中的险种的标准订单JSON数据
      chooseRiskStandardOrder: {
        data: [],
        list: []
      },
      supplierPortList: [],
      allListSupplierList: [],
      changeInputValue: [],
    };
  },
  computed: {
    getFieldTypeName() {
      return function (type) {
        if (!type) return '';
        return this.fieldTypeList.find(item => item.value == type)?.name || '';
      }
    },

    getRowKey() {
      return this.queryParams.type == 4 ? 'originalId' : 'id';
    }

  },
  watch: {
    supplierExcPort: function (val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    // 获取服务方方法列表
    this.getExcPortList();
    // 获取服务方及服务方下的接口
    this.getSuppliderAndExcPort();

    // 获取服务方入参的数据
    this.getRisksTreeData();

    // 切换映射值字段的焦点
    let direction = this.$getDirection();
    direction.on('keyup', function (e, val) {
      let codeObj = [
        {code: '37', name: 'previous'},
        {code: '38', name: 'previousLine'},
        {code: '39', name: 'next'},
        {code: '40', name: 'nextLine'}
      ];

      let obj = codeObj.find(item => item.code == e.keyCode);

      obj && direction[`${obj.name}`]();
    });


    const timer = setInterval(()=>{
      this.handleSumbitMappingFormula();
    }, 2000);

    this.$once("hook:beforeDestory", ()=>{
      clearInterval(timer);
    })
  },
  methods: {
    getRisksTreeData() {
      if (!this.queryParams.portId) {
        this.fieldRisks = [];
        return;
      }

      let data = [];
      let params = {
        portId: this.queryParams.portId,
        type: 4,
        pageNum: 1,
        pageSize: 1000
      };

      listExcPortConfig(params).then(response => {
        data = list2FieldTree(response.rows, 2);

        this.fieldRisks = data;
      });
    },

    /**
     *  获取服务方方法列表
     */
    async getExcPortList() {
      let res = await listExcPort();
      if (res.code == 200) {
        this.excPortList = res.rows;
      }
    },

    /**
     * 获取服务方接口的树形方法
     */
    async getSuppliderAndExcPort() {
      // 获取服务方列表
      const res = await listSupplier({supplierName: this.supplierName});

      // 获取接口列表
      const excPortRes = await listExcPort();

      // 将接口按服务方进行分组
      this.supplierPortList =  res.rows?.map(supplier=>{
        return {
          ...supplier,
           label:supplier.supplierName,
           children:this.getSupplierChildern(excPortRes.rows, supplier),
        };
      });
    },

    getSupplierChildern(data, supplier) {
      const {supplierId} = supplier;
      let children = [];
      data.forEach(port=>{
        if(port.supplierId == supplierId) {
          children.push({
            ...port,
            label: port.portName,
            supplierType: supplier.supplierType
          });
        }
      })

      return children;
    },


    /** 查询接口参数配置列表 */
    getList() {
      this.loading = true;

      if (!this.queryParams.portId) {
        this.loading = false;
        this.excPortOriginalList = [];
        this.excPortConfigList   = [];
        return;
      }

      listExcPortConfig(this.queryParams).then(response => {

        this.excPortOriginalList = JSON.parse(JSON.stringify(response.rows));

        let excPortTreeList = dealExcPortTree(response.rows, 100);

        // console.log('excPortTreeList为', excPortTreeList);

        // 排序
        this.excPortConfigList = this.excPortTreeSortList(excPortTreeList);

        this.total = response.total;
        this.loading = false;
      });

    },


    /**
     * 数据按orderNum 进行排序
     * @param data
     */
    excPortTreeSortList(data) {
      data.sort((obj1, obj2) => {
        return obj1.orderNum - obj2.orderNum;
      });

      data.map(item=>{
        if(Array.isArray(item.children)) {
          item.children = this.excPortTreeSortList(item.children);
        }
        return item;
      })

      return data;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        portId: null,
        ancestors: null,
        parentId: null,
        fieldName: null,
        type: null,
        column: null,
        columnType: null,
        defaultValue: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该接口的数据字段吗？').then(function () {
        return delExcPortConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pm/excPortConfig/export', {
        ...this.queryParams
      }, `excPortConfig_${new Date().getTime()}.xlsx`)
    },

    // 树形结构点击方法
    handleNodeClick(data) {
      // console.log('选中的数据data为', data);
      this.chooseExcPort.id = data.id || '';
      this.chooseExcPort.name = data.label || '';
      this.chooseExcPort.supplierType = data.supplierType || '';
      /*this.chooseExcPort = {
        id: data.id || '',
        name: data.label || '',
        supplierType: data.supplierType || ''
      };*/

      // 判断生成右侧的树形结构
      /*if (data.supplierType) {
        this.getFieldTree();
      }*/

      /*if(data.supplierId) {
        // 获取字段处理方法
        this.getFiledFunction(data.supplierId);
      }*/

      this.importConfig.disabled = !data.id;
      this.queryParams.portId = data.id;
      this.deleteButtonStatus = !data.id;


      this.getList();
      //this.getRisksTreeData();
    },

    // 切换参数类型时的变化
    changeExcPortType() {
      this.chooseExcPort.type = this.queryParams.type;
      let portObj = this.extPortConfigType.find(item => item.value == this.chooseExcPort.type);
      this.chooseExcPort.typeName = portObj.name;

      //this.importConfig.disabled = this.chooseExcPort.type == 3;

      //this.getFieldTree();
      this.getList();
    },

    // 删除操作
    delExcPortConfigType() {
      let {id, name, type, typeName} = this.chooseExcPort;

      type = type || 1;

      this.$modal.confirm(`是否确认删除接口'${name}'下的类型为:${typeName}的数据字段吗？`).then(function () {
        return delExcPortConfigType(id, type);
      }).then((res) => {

        // this.$message[`${res.code == 200 ? 'success' : 'error'}`](res.msg);
        this.$message({
          type: res.code == 200 ? 'success' : 'error',
          message: res.msg
        });

        this.getList();
      }).catch((error) => {
        // console.log(error);
      });
    },

    /**
     * 新增字段
     * @param row 选中的数据
     * @param type 新增的类型： 1: 新增同级; 2 : 新增子级
     */
    handleFiledAdd(row, type) {
      this.fieldDialog.open = true;
      this.resetFieldForm();

      if (type == 1) {
        this.fieldForm = {
          parentId: row.parentId,
          ancestors: `${row.parentId},${row.ancestors}`,
          portId: this.chooseExcPort.id,
          type: this.chooseExcPort.type
        };

        this.parentFieldName = '主级别';
      } else {
        this.parentFieldName = row.field;

        this.fieldForm = {
          parentId: row.id,
          ancestors: `${row.id},${row.ancestors}`,
          portId: this.chooseExcPort.id,
          type: this.chooseExcPort.type
        };
      }
    },

    // 重置新增的表单数据
    resetFieldForm() {
      this.fieldForm = {
        parentId: '',
        ancestors: '',
        field: '',
        fieldName: '',
        fieldType: 1
      }
    },

    // 提交新增字段
    submitFieldForm() {
      this.$refs['fieldForm'].validate(valid => {
        if (valid) {
          addExcPortConfig(this.fieldForm).then(res => {
            this.$message({
              type: res.code == 200 ? 'success' : 'error',
              message: res.msg
            });

            this.fieldDialog.open = false;
            this.getList();
          });
        }
      })
    },

    // 修改字段
    handleFiledUpdate(row) {
      this.reset();
      let id;

      if(this.queryParams.type == 4) {
        id = row.originalId
      } else {
        id = row.id || this.ids;
      }

      getExcPortConfig(id).then(response => {
        this.updateForm = response.data;

        this.updateField.open = true;
        this.updateField.title = "修改接口参数配置";
      });
    },


    /**
     * 修改字段的回调
     * @param res
     */
    updateFieldForm(res) {
      let flag = res.code == 200 ? 'success' : 'error';

      this.$message[flag](res.msg);
      this.getList();
      this.updateField.open = false;
    },

    // 修改字段取消操作
    cancelFieldForm(res) {
      this.updateField.open = res;
    },

    // 获取标准字段树形结构
    getFieldTree() {
      // 服务方出参不需要生成
      if (this.chooseExcPort.type == 2) return;

      // 标准出参的数据要从填写的服务方参里面取
      if ([3, 4].includes(this.chooseExcPort.type)) {
        // 标准出参获取tree格式
        this.getFieldRisksTree();
      } else {
        // 服务方入参tree数据
        this.getRisksTreeData();
      }
    },

    getFieldRisksTree() {
      let params = {
        type: 2,
        pageNum: 1,
        pageSize: 1000,
        portId: this.chooseExcPort.id
      };

      listExcPortConfig(params).then(res => {
        let data = res.code == 200 ? res.rows : [];

        this.fieldRisks = list2FieldTree(data);
      });
    },

    // 获取焦点选中字段
    handleFocusFormula(row, el) {
      this.chooseFieldData = row;
    },

    // 获取选中的data
    updateMappingFormula(data) {
      let rowKey = this.chooseFieldData?.rowKey;
      if (!rowKey) return;

      let path = data?.path;

      // 修改列表数组值，方便后面的提交操作
      this.handleChangeInputValue(path, rowKey);

      this.$refs[rowKey].value = path;
      this.$refs[rowKey].focus();
    },

    handleChangeInputValue(path, rowKey) {
      let type = this.getRowKey;

      this.excPortOriginalList.forEach(item => {
        if (item[type] == rowKey) {
          if(item.mappingFormula !== path) {
            const {mappingFormula, originalId, id, ...param} = item;

            let changeKey;
            if(type == 'originalId') {
              changeKey = this.changeInputValue.findIndex(d=>d.originalId == originalId);
            } else {
              changeKey = this.changeInputValue.findIndex(d=>d.id == id);
            }

            // console.log('changeKey为', changeKey);

            if(changeKey === -1) {
              this.changeInputValue.push({
                mappingFormula: path,
                originalId,
                id,
                ...param
              });
            } else {
              this.changeInputValue[changeKey] = {
                mappingFormula: path,
                originalId,
                id,
                ...param
              };
            }
          }
        }
      });

    },

    // 提交映射值信息
    async handleSumbitMappingFormula() {

      if(this.changeInputValue && this.changeInputValue.length > 0 ) {
        if(this.chooseExcPort.type == 4) {
          const res = await  addStandardOrderList(this.queryParams.portId, this.changeInputValue);
          if(res.code == 200) {
            this.changeInputValue.forEach(item=>{
              const index = this.excPortOriginalList.findIndex(d=>d.originalId == item.originalId);
              if(index !== -1){
                this.excPortOriginalList.splice(index, 1, item);
              }
            });
          }

          this.changeInputValue = [];
        } else {
          const res = await updateExcPortConfigMappingFormula(this.changeInputValue);

          if(res.code == 200) {
            this.changeInputValue.forEach(item=>{
              const index = this.excPortOriginalList.findIndex(d=>d.id == item.id);
              if(index !== -1){
                this.excPortOriginalList.splice(index, 1, item);
              }
            });
          }

          this.changeInputValue = [];
        }
      }

    },


    /**
     * 执行排序操作
     * @param row 要操作的数据
     * @param type 排序的类型。up: 向上; down: 向下
     */
    handleSort(row, type) {
      let {id: idOld, orderNum: orderNumOld, field: filedOld, parentId: parentIdOld} = row;

      let list = this.getExcPortHandleSort(this.excPortOriginalList, parentIdOld);
      let [keyNew, length] = [ 0, list.length];

      const keySort = list.findIndex(item=>item.id == idOld) || 0;


      if (type == 'up') {
        keyNew = keySort != 0 ? keySort - 1 : 0;
      } else if (type == 'down') {
        keyNew = keySort != length - 1 ? keySort + 1 : length - 1;
      }

      // 获取要交换排序的字段
      let keyNewObj = list[keyNew];

      let listSort = [
        {id: idOld, orderNum: orderNumOld, field: filedOld},
        {id: keyNewObj.id, orderNum: keyNewObj.orderNum, field: keyNewObj.field}
      ];

      updateExcPortConfigOrderNum(listSort).then(res => {
        this.$message[`${res.code == 200 ? 'success' : 'error'}`](res.msg);
        this.getList();
      });
    },

    // 查找要改变的数据和序号
    getExcPortHandleSort(data, parentId) {
      let newArr = data.filter(item => item.parentId == parentId);
      newArr.sort((obj1, obj2) => obj1.orderNum - obj2.orderNum);

      return newArr;
    },

    // 标准订单JSON查看规则
    handleRule() {
      this.$router.push({
        path: "/supplier/excPortUpdateCondition",
        query: {
          portId: this.queryParams.portId,
          portName: this.chooseExcPort.name
        }
      })
    },

    // 修改映射值操作
    handleInputValue(rowKey) {
      // input的值为
      const value = this.$refs[rowKey].value;

      this.handleChangeInputValue(value, rowKey);
    },

    // 获取字段处理方法
    async getFiledFunction(supplierId) {
      const res = await getAlllistSupplierMain(supplierId);
      this.allListSupplierList = res?.data ?? [];
    }

  },
};
</script>

<style lang="scss" scoped>
.mappingFormulaInput {
    width: 120px !important;
}
</style>
